package com.multi.framework.aspectj;

import com.multi.common.annotation.DataSource;
import com.multi.source.domain.BkDataSourceInfo;
import com.multi.source.util.DataBaseUtils;
import com.multi.source.vo.DataSourceInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Description
 * @ClassName DataSourceAspect
 * @Author pzj
 * @Data 2024/11/28 15:06
 */

@Slf4j
@Aspect
@Component
public class DataSourceAspect {


    @Autowired
    private DataBaseUtils dataBaseUtils;

    //在任务开始之前创建数据库连接
    @Before("@annotation(dataSource)")
    public void deBefore(JoinPoint jp, DataSource dataSource) {
        log.info("进入切片创建数据库连接");
        Object arg = jp.getArgs()[0];
        //强转获取DataSourceInfoVo信息
        DataSourceInfoVo dataSourceInfoVo = (DataSourceInfoVo) arg;
        BkDataSourceInfo bkDataSourceInfo=new BkDataSourceInfo();
        BeanUtils.copyProperties(dataSourceInfoVo,bkDataSourceInfo);
        //动态创建数据库连接
        dataBaseUtils.createConnect(bkDataSourceInfo,"mysql");
        dataBaseUtils.createConnect(bkDataSourceInfo);
    }


    //在任务处理结束后断开临时数据库连接信息
    @After(value = "@annotation(dataSource)")
    public void after(JoinPoint jp,DataSource dataSource) {
        log.info("销毁数据库连接信息");
        DataSourceInfoVo dataSourceInfoVo = (DataSourceInfoVo) jp.getArgs()[0];
        dataBaseUtils.deleteConnect(dataSourceInfoVo.getDbIp());
    }
}
